//
//  IntegralIndex.swift
//  LeGou
//
//  Created by lxm on 2022/10/31.
//

import UIKit
import JXPagingView
import JXSegmentedView
class IntegralIndex:  ZMViewController, SubScrollDelegate, HomeHotFlowLayoutDelegate, ListRequestObjct, XMIndexHeaderViewDelegate {
    //MARK: --------------------属性--------------------
    var scrollViewDidScrollBlock: ((UIScrollView) -> ())?
//    var dataArray = ["朋森豆浆",
//                     "朋森豆浆机迷你家豆浆机迷你家豆浆机迷你家用奢侈款",
//                     "朋森豆浆机迷你家豆浆浆",
//                     "朋森豆浆机迷你家豆浆",
//                     "朋森豆浆机迷你家",
//                     "朋森豆浆机迷你家豆浆机迷用奢侈款",
//                     "朋森豆浆机迷你迷你家豆浆机迷你家豆浆机迷你家用奢侈款家豆浆机迷你家豆浆机迷你家用奢侈款"]
    var typeId = 0
    var isGussLike = false
    var listData = [VIPMallModels.Goods]()
    var openHeaderRefresh = false
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        return collectionView
    }
    
    var cates = [("全部", 0), ("0-200", 1), ("200-500", 2), ("500以上", 3)]
    
    var seg : XMIndexHeaderView!

    var integralBtn = IntegralButton()
    
    var type = 0
    
    //MARK: --------------------UI控件--------------------
    var collectionView : UICollectionView!
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadList()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = ""
        let layout = HomeHotFlowLayout()
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 16, left: 12, bottom: 18, right: 12)
        layout.minimumLineSpacing = 7
        layout.minimumInteritemSpacing = 7
        layout.delegate = self
        collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
        collectionView.register(UINib(nibName: "VIPMallGoodsCell", bundle: nil), forCellWithReuseIdentifier: "VIPMallGoodsCell")
        view.addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        view.backgroundColor = .clear
        collectionView.alwaysBounceVertical = true
        collectionView.showsVerticalScrollIndicator = false
        
        addRefresh(scrollView: collectionView, addHead: openHeaderRefresh, addFoot: true) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        
        let config  = XMIndexHeaerViewConfig()
        config.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        config.fontColor  = UIColor.zm.color999999()
        config.selectFont = UIFont.systemFont(ofSize: 14, weight: .medium)
        config.selectFontColr = UIColor.zm.color333333()
        config.lineViewCornerRadius = 1.5
        
        seg = XMIndexHeaderView(frame: CGRect(x: 0, y: 0, width: SCREEN_W - 80, height: 44), withTitleArray:cates.map({$0.0}), animation: false)!
        seg.lineColor = Style.mainColor
        seg.backGroundColor = view.backgroundColor
        seg.lineWidth = 17
        seg.minimumLineSpacing = 24
        seg.shouldAspect = true
        seg.config = config
        seg.delegateXM = self
        seg.hideLine = true
        seg.inset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        
        view.addSubview(seg)
        
        view.addSubview(integralBtn)
        
        view.addSubview(collectionView)
        
        integralBtn.zm.addTap(target: self, selector: #selector(onTapIntegral))
    }
    
    func addConstraints() {
        collectionView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(seg.snp.bottom)
        }
        
        integralBtn.snp.makeConstraints { make in
            make.centerY.equalTo(seg)
            make.right.equalToSuperview().offset(-15)
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
    }
    
    @objc func onTapIntegral() {
        let n = integralBtn.nextState()
        collectionView.mj_header?.beginRefreshing()
    }
    
    func giveSize(titleStr : String) -> CGSize {
//        let imageStr = getAtrStr(titleStr: titleStr)
        let cellWidth = (SCREEN_W - 24 - 7 ) / 2
        let width = cellWidth - 24
        let f = (titleStr as NSString).boundingRect(with: CGSize(width: width, height: 300), options: .usesLineFragmentOrigin, attributes: [.font : UIFont.systemFont(ofSize: 14, weight: .medium)], context: nil)
        return f.size
    }
    
    func loadList() {
        var pa = ["cid" : typeId, "limit" : pageSize, "page" : page] as [String : Any]
        if self.cates[seg.currentINdex].1 > 0 {
            pa["integralType"] = self.cates[seg.currentINdex].1
        }
        if integralBtn.state > 0 {
            pa["priceOrder"] = integralBtn.state == 1 ? "asc" : "desc"
        }
        let api = VIPMallAPI.integralGoods(pa)
        ZMUtil.listRequest(type: VIPMallModels.Goods.self, api: api) { resp in
            self.listRequest(resp)
        }
    }

    //MARK: --------------------delegate--------------------
    func xmIndexHeaderViewDidselected(with index: Int, indexView indexheaderView: XMIndexHeaderView!) {
        collectionView.mj_header?.beginRefreshing()
    }
    
    func scrollView() -> UIScrollView {
        return self.collectionView
    }
    
    func scrollViewDidScroll(_ scrollViewDidScorllBolck: @escaping ((UIScrollView) -> ())) {
        scrollViewDidScrollBlock = scrollViewDidScorllBolck
    }
    // 处理手势被吃
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        checkBottomSpace()
    }
    // 处理手势被吃
    func checkBottomSpace() {
        let y = collectionView.contentOffset.y
        if y == collectionView.contentSize.height - collectionView.zm.height {
            collectionView.contentOffset = CGPoint(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y - 1)
        }
    }
    // 处理手势被吃
    func minContentHeight() -> CGFloat {
        return view.zm.height + 1
    }
}

extension IntegralIndex : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let data = listData[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VIPMallGoodsCell", for: indexPath) as! VIPMallGoodsCell
        cell.label.text = data.storeName
        cell.rmb.isHidden = typeId == -1
        if typeId == -1 {
            let priceStr = data.integralPrice.zm.toString(keep: 2) + "积分"
            let attrString = NSMutableAttributedString(string: priceStr)
            attrString.addAttributes([.font: UIFont.zm.fontMedium(size: 12)], range: NSRange(location: priceStr.count - 2, length: 2))
            cell.price.attributedText = attrString
            cell.interests.isHidden = true
        } else {
            cell.price.text = data.price.zm.toString(keep: 2)
            cell.interests.isHidden = false
        }
        cell.activityNum.setTitle("+\(data.giveActivity.zm.toString(keep: 4))活跃度", for: .normal)
        cell.activityNum.isHidden = data.giveActivity == 0
        cell.tan.isHidden = data.giveActivity == 0
//        cell.activityNum.layoutSubviews()
        cell.layoutIfNeeded()
        cell.saleCount.text = "销量:\(data.ficti+data.sales)"
        cell.img.zm.setImage(urlStr: data.image)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width : CGFloat = (SCREEN_W - 24 - 7) / 2
        let d = listData[indexPath.row]
        let size = giveSize(titleStr: d.storeName)
//        print("size is ", size)
        return CGSize(width: width, height: width + 12 + size.height + (typeId != -1 ? 90 : 60))  // 20 是已售 //+ (isMili ? 0 : 0))
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = listData[indexPath.row]
        router.push("xm://main/VIPMall/goods_detail", context: ["id" : data.id])
    }
}

extension IntegralIndex : JXPagingViewListViewDelegate {
    func listScrollView() -> UIScrollView { collectionView }
    
    func listView() -> UIView {
        return view
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let scrollViewDidScrollBlock = scrollViewDidScrollBlock {
            scrollViewDidScrollBlock(scrollView)
        }
        listViewDidScrollCallback?(scrollView)
    }
}


class IntegralButton : UIView {
    var state = 0 {
        didSet {
           update()
        }
    }
    
    var label = ZMUtil.label(title:"积分排序", color: UIColor.zm.color999999(), font: UIFont.systemFont(ofSize: 14))
    
    var icon = ZMUtil.imageView(imageName: "")
    
    let stack = ZMUtil.stackView(axis: .horizontal)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUI()
    }
    
    func setUI() {
        update()
        stack.addArrangedSubview(label)
        stack.addArrangedSubview(icon)
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        icon.snp.makeConstraints { make in
            make.width.height.equalTo(16)
        }
    }
    
    func nextState() -> Int {
        state += 1
        if state > 2 {
            state = 0
        }
        return state
    }
    
    func update() {
        var name = "arrow_none"
        if state == 0 {
            name = "arrow_none"
        } else if state == 1 {
            name = "arrow_up"
        } else if state == 2 {
            name = "arrow_down"
        }
        icon.image = UIImage.init(named: name)
        icon.sizeToFit()
    }
}
